#!/bin/bash
# Copyright 2019-2024 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================

set -e

BASEPATH=$(cd "$(dirname $0)"; pwd)
OUTPUT_PATH="${BASEPATH}/output"
BUILD_PATH="${BASEPATH}/build/"

# print usage message
usage() {
  echo "Usage:"
  echo "  sh build.sh [-j<N>] [-h|--help] [-v|--verbose] [--ascend_custom_path=<PATH>]"
  echo "              [--output_path=<PATH>]"
  echo ""
  echo "Options:"
  echo "    -h, --help     Print usage"
  echo "    -v, --verbose  Display build command"
  echo "    -j<N>          Set the number of threads used for building Parser, default is 8"
  echo "        --ascend_custom_path=<PATH>"
  echo "                   Set ascend package install path, default /usr/local/Ascend/latest"
  echo "                   Set build metadef or use released package, default on"
  echo "        --output_path=<PATH>"
  echo "                   Set output path, default ./output"
  echo ""
}

# check value of input is 'on' or 'off'
# usage: check_on_off arg_value arg_name
check_on_off() {
  arg_value="$(echo $1 | tr '[A-Z]' '[a-z]')"
  if [ "X$arg_value" != "Xon" ] && [ "X$arg_value" != "Xoff" ]; then
    echo "Invalid value $arg_value for option -$2"
    usage
    exit 1
  fi
}

# parse and set options
checkopts() {
  VERBOSE=""
  THREAD_NUM=8
  ENABLE_GITEE="off"
  ASCEND_CUSTOM_PATH="/usr/local/Ascend/latest"
  BUILD_METADEF="on"

  # Process the options
  parsed_args=$(getopt -a -o j:hv -l help,verbose,ascend_custom_path:,output_path: -- "$@") || {
    usage
    exit 1
  }

  eval set -- "$parsed_args"

  while true; do
    case "$1" in
      -h | --help)
        usage
        exit 0
        ;;
      -j)
        THREAD_NUM="$2"
        shift 2
        ;;
      -v | --verbose)
        VERBOSE="VERBOSE=1"
        shift
        ;;
      --ascend_custom_path)
        ASCEND_CUSTOM_PATH="$2"
        shift 2
        ;;
      --output_path)
        OUTPUT_PATH="$(realpath $2)"
        shift 2
        ;;
      --)
        shift
        break
        ;;
      *)
        echo "Undefined option: $1"
        usage
        exit 1
        ;;
    esac
  done
}

mk_dir() {
  local create_dir="$1"  # the target to make
  mkdir -pv "${create_dir}"
  echo "created ${create_dir}"
}

# create build path
build_parser() {
  echo "create build directory and build Parser";
  mk_dir "${BUILD_PATH}"
  cd "${BUILD_PATH}"
  cmake -D ENABLE_OPEN_SRC=True \
        -D ENABLE_GITEE=${ENABLE_GITEE} \
        -D BUILD_METADEF=${BUILD_METADEF} \
        -D BUILD_WITHOUT_AIR=True \
        -D ASCEND_CUSTOM_PATH=${ASCEND_CUSTOM_PATH} \
        -D CMAKE_BUILD_TYPE=Release \
        -D CMAKE_INSTALL_PREFIX=${OUTPUT_PATH} \
        ..
  if [ 0 -ne $? ]; then
    echo "execute command: cmake .. failed."
    return 1
  fi

  make ${VERBOSE} -j${THREAD_NUM} && make install && make package

  if [ 0 -ne $? ]; then
    echo "execute command: make ${VERBOSE} -j${THREAD_NUM} && make install failed."
    return 1
  fi
  echo "Parser build success!"
}

main() {
  cd "${BASEPATH}"
  checkopts "$@"

  if [ "X$BUILD_METADEF" = "Xon" ] || [ "X$BUILD_METADEF" = "XON" ]; then
    git submodule update --init metadef
  fi

  g++ -v
  mk_dir "${OUTPUT_PATH}"

  # Parser build start
  echo "---------------- Parser build start ----------------"
  build_parser || { echo "Parser build failed."; exit 1; }
  echo "---------------- Parser build finished ----------------"
}

main "$@"
